package com.aipolice.web.face;

import com.aipolice.pojo.face.UserFaceInfoBean;
import com.aipolice.service.face.FaceSearchService;
import com.aipolice.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
public class FaceController {
    @Autowired
    FaceSearchService faceSearchService;
    @PostMapping(value = "/face")
    public UserFaceInfoBean add(UserFaceInfoBean bean,String user_id ,MultipartFile image, HttpServletRequest request) throws Exception {
        String path = saveOrUpdateImageFile(bean, image, request);
        faceSearchService.add(path,user_id ,bean);
        System.out.println(bean);
        return bean;
//        saveOrUpdateImageFile(bean, image, request);

    }

    @GetMapping(value = "/face")
    public String faces(){
        // groupid 另设测试为testGroup
        return faceSearchService.getUsers("testGroup");
    }

    @DeleteMapping("/face/{id}")
    public void delete(@PathVariable("id") String id) throws Exception {
        System.out.println("删除方法");
        faceSearchService.delete(""+id);
    }

    public String saveOrUpdateImageFile(UserFaceInfoBean bean, MultipartFile image, HttpServletRequest request)
            throws IOException {
        File imageFolder= new File(request.getServletContext().getRealPath("img/face"));
        File file = new File(imageFolder,bean.getBirthday()+".jpg");
        System.out.println(file.getAbsolutePath());
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        image.transferTo(file);
        BufferedImage img = ImageUtil.change2jpg(file);
        ImageIO.write(img, "jpg", file);
        return file.getAbsolutePath();
    }
}
